package cn.icyzx.dao;

import cn.icyzx.exception.WorkException;
import cn.icyzx.models.*;

import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import cn.icyzx.util.CommonUtil;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by 郑凯 on 2016/9/1.
 */
@Repository
public class DaoWorks {
    @Autowired
    UserMapper userMapper;

    @Autowired
    WorkMapper workMapper;

    @Autowired
    Work work;

    private static Logger logger = Logger.getLogger(DaoWorks.class);

    /**
     * getWorksSum 根据条件获取产品的总数
     *
     * @param condition 查询条件
     * @return int
     */
    public int getWorksSum(Map<String, String> condition) {
        return workMapper.getWorksSum(condition);
    }

    /**
     * listWorks 结果集
     *
     * @param condition 查询条件
     * @return java.cn.icyzx.util.List<cn.icyzx.models.Work>
     */
    public List<Work> getListWorks(Map<String, String> condition) throws WorkException {

        List<Work> listWorks = workMapper.getListWorks(condition);

        for (Work work : listWorks) {
            work.setCollectionNumber(workMapper.getCollectionNumberByWid(work.getWid()));
            work.setRecommendNumber(workMapper.getRecommendNumberByWid(work.getWid()));
            work.setCommentNumber(workMapper.getlistCommentsNumberByWid(work.getWid()));

            String time = CommonUtil.getTimeAgo(work.getPublicTime().getTime()); //这是计算帖子发了多久前，如有更好的想法，联系我
            work.setAgo(time);
        }

        return listWorks;
    }

    public List<Work> getHotWork() throws WorkException {
        return workMapper.getHotWork();
    }

    /**
     * 增加浏览数操作
     *
     * @param wid
     * @throws WorkException
     */
    public void over(String wid) throws WorkException {
        if (workMapper.over(wid) <= 0)
            throw new WorkException("over--找不到该wid");
    }

    /***
     *  判断是否已推荐
     * @param wid
     * @param uid
     * @return 返回状态
     */
    public boolean isRecommend(String wid, String uid) {

        try {
            if (workMapper.isRecommend(wid, uid) > 0)
                return true;
            else
                return false;
        } catch (Exception e) {
            logger.error("is Recommend error");
            e.printStackTrace();
            return false;
        }
    }

    public boolean isCollection(String wid, String uid) {
        try {
            if (workMapper.isCollection(wid, uid) > 0)
                return true;
            else return false;
        } catch (Exception e) {
            logger.error("is collection error");
            e.printStackTrace();
            return false;
        }
    }

    /*** 用户对作品其他操作
     *
     * @param uid uid
     * @param wid wid
     * @param type 关于作品的操作（收藏，推荐）
     * @return boolean
     */
    public boolean addWorkOperate(String wid, String uid, String type) {
        try {
            if (type.equals("recommend")) {
                if (isRecommend(wid, uid)) {
                    workMapper.removeFromWorkStore(wid, uid, type);
                    logger.info("remove :" + type + " wid");
                    return true;
                }

            } else if (type.equals("collection")) {
                if (isCollection(wid, uid)) {
                    workMapper.removeFromWorkStore(wid, uid, type);
                    logger.info("remove :" + type + " wid");
                    return true;
                }
            } else
                logger.warn("unknown workOperate type");

            workMapper.insertToWorkStore(wid, uid, type);
            logger.info("insert :" + type + " wid");
            return true;
        } catch (Exception e) {
            logger.error("insert into work_store error");
            e.printStackTrace();
            return false;
        }
    }

    public Work getWorkByWid(String wid) throws WorkException {
        try {
            Work work = workMapper.getWorkByWid(wid);
            String time = CommonUtil.getTimeAgo(work.getPublicTime().getTime());
            work.setAgo(time);

            work.setCollectionNumber(workMapper.getCollectionNumberByWid(work.getWid()));
            work.setRecommendNumber(workMapper.getRecommendNumberByWid(work.getWid()));
            work.setCommentNumber(workMapper.getlistCommentsNumberByWid(work.getWid()));
            return work;
        } catch (Exception e) {
            logger.error("get work by wid error" + e.getMessage());
            throw new WorkException("根据wid获取work错误");
        }
    }

    public boolean commentWork(String wid, String uid, String info) {
        try {

            Comment comment = new Comment();
            comment.setCommentsId(String.valueOf(new Date().getTime()));
            comment.setWid(wid);
            comment.setUid(uid);
            comment.setInfo(info);

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String now = simpleDateFormat.format(new Date());
            Date date = simpleDateFormat.parse(now);
            comment.setTime(date);

            userMapper.insertComments(comment);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * listComments 通过作品的wid，获取对应的评论
     *
     * @param wid 作品wid
     * @return java.cn.icyzx.util.List<cn.icyzx.models.Comment> 封装好的User,评论时间，内容
     */
    public List<Comment> getlistCommentsByWid(String wid) {
        List<Comment> commentList = workMapper.getlistCommentsByWid(wid);
        for (Comment comment : commentList) {
            comment.setAgo(CommonUtil.getTimeAgo(comment.getTime().getTime()));
        }
        return commentList;
    }

    /*** 添加work
     *
     * @param jsonWork
     * @throws SQLException
     */
    public void insertWork(JSONObject jsonWork) throws WorkException {
        work.setWid((String) jsonWork.get("wid"));
        work.setUid((String) jsonWork.get("uid"));
        work.setName((String) jsonWork.get("title"));
        work.setInfo((String) jsonWork.get("content"));
        work.setPublicTime(new Date());

        workMapper.insertWork(work);
    }

    /**
     * 通过uid获取作品的个数
     *
     * @param uid
     * @return
     */
    public int getWorksNumberByUid(String uid) {
        return workMapper.getWorkNumberByUid(uid);
    }

    /**
     * 通过uid获取评论的个数
     *
     * @param uid
     * @return
     */
    public int getCommentsNumberByUid(String uid) {
        return workMapper.getCommentsNumberByUid(uid);
    }

    /**
     * 通过uid获取收藏的个数
     *
     * @param uid
     * @return
     */
    public int getCollectionNumberByUid(String uid) {
        return workMapper.getCollectionNumberByUid(uid);
    }

    /**
     * 通过uid获取推荐的个数
     *
     * @param uid
     * @return
     */
    public int getRecommendNumberByUid(String uid) {
        return workMapper.getRecommendNumberByWid(uid);
    }
}
